package com.zhaojun.netty.helloworld2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;

/**
 * Created by asus on 2017/9/24.
 */
public class Server {

    public static void main(String[] args) {
        NioEventLoopGroup boss=new NioEventLoopGroup();
        NioEventLoopGroup worker=new NioEventLoopGroup();
        ServerBootstrap bootstrap=new ServerBootstrap();
        bootstrap.group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                     //.addLast(new FixedLengthFrameDecoder(13))
                                     .addLast(new LineBasedFrameDecoder(1024))//行解码器
                                     .addLast(new StringEncoder())//编码器 将字符串编码成二进制数据
                                     .addLast(new StringDecoder())//解码器 将二进制数据解码成 字符串
                                     .addLast(new ChannelInboundHandlerAdapter(){
                                         @Override
                                         public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                             String msgStr= (String) msg;
                                             System.out.println(msgStr);
                                            // ByteBuf resp= Unpooled.copiedBuffer(("回复接收"+msgStr).getBytes("utf-8"));
                                             ctx.writeAndFlush("回复接收"+msgStr);
                                         }

                                         @Override
                                         public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                             ctx.close();
                                         }
                                     });
                    }
                });


        try {
            ChannelFuture f = bootstrap.bind(8888).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
